<template>
  <div class="h-full bg-white">
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" class="mr-1" @click="handleAdd" v-if="canAdd">
          <template #icon><PlusOutlined /></template>
          {{ btnAddName }}
        </a-button>
        <a-button
          type="primary"
          class="mr-1"
          @click="handleEdit"
          v-if="canEdit && listPage.isColCheckboxShow"
        >
          <template #icon><EditOutlined /></template>
          {{ btnEditName }}
        </a-button>
        <Popconfirm
          placement="top"
          title="确定删除吗？"
          ok-text="确定"
          cancel-text="取消"
          @confirm="deleteBatch"
        >
          <a-button type="primary" class="mr-1" v-if="canDel && listPage.isColCheckboxShow">
            <template #icon><DeleteOutlined /></template>
            {{ btnDelName }}
          </a-button>
        </Popconfirm>
        <a-button type="primary" class="mr-1" v-if="listPage.isAdmin" @click="handleManager">
          <template #icon><SettingOutlined /></template>
          管理
        </a-button>
      </template>
      <template #bodyCell="{ record }">
        <div
          v-for="(row, indexr) in pageSetup"
          :key="indexr"
          class="cursor-pointer"
          @click="handleClick(record)"
        >
          <Row>
            <Col
              v-for="(col, colc) in row.blocks"
              :key="colc"
              :span="col.width * 2"
              class="overflow_text"
            >
              <div v-if="col.type == 'field'" :style="col.style">
                <span
                  :style="{
                    ...col.style,
                  }"
                >
                  <span
                    v-if="col.fontIcon"
                    :class="col.fontIcon ? 'fa ' + col.fontIcon : 'fa-phone'"
                  ></span
                  >{{ '  ' }}
                  <span
                    v-html="
                      col.label && col.label.indexOf('%s') == -1
                        ? col.label
                        : col.label.replace('%s', record[col.fieldName])
                    "
                  >
                  </span>
                  <span v-if="record[col.fieldName] && col.label.indexOf('%s') == -1">
                    <span v-html="record[col.fieldName]"></span>
                  </span>
                </span>
              </div>
              <div v-else-if="col.type == 'comb'" :style="col.style">
                {{ record['combFields']?.filter((it) => it.blockId == col.blockId)[0]?.text }}
              </div>
              <div
                v-else-if="col.type == 'button'"
                :style="col.style"
                @click.stop="handleColOperate(col, record)"
              >
                <span
                  v-if="col.fontIcon"
                  :class="col.fontIcon ? 'mr-1 fa ' + col.fontIcon : 'fa-phone'"
                ></span>
                <span>
                  {{ col.btnName }}
                </span>
              </div>
              <div v-else-if="col.type == 'text'" :style="col.style">
                {{ col.label }}
              </div>
              <div
                v-else-if="col.type == 'img'"
                :style="{ ...col.style, width: '100%', height: '20px' }"
              >
                <Image style="width: 100%; height: 100%" :src="col.imgUrl" />
              </div>
              <div v-else-if="col.type == 'blank'"></div>
              <div v-else-if="col.type == 'line'" :style="col.style">
                <div class="line" :style="{ borderColor: col.fontColor }"></div>
              </div>
            </Col>
          </Row>
        </div>
        <div>
          <Col class="text-right w-full pt-2">
            <GiveLike
              v-if="listPage['likeMode']"
              :moduleCode="listPage.moduleCode"
              :moduleId="record.id"
              :mode="listPage['likeMode']"
            />
          </Col>
        </div>
      </template>
    </BasicTable>
    <ProcessShowDrawer @register="registerProcessShowDrawer" @handle-current="handleEditFlow" />
    <ProcessDrawer @register="registerProcessDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, onMounted, ref, unref, nextTick, computed, h } from 'vue';
  import { BasicTable, useTable } from '/@/components/Table';
  import { getVisualList, getVisualDel, getVisualListRelate } from '/@/api/module/module';
  import {
    SettingOutlined,
    DeleteOutlined,
    PlusOutlined,
    EditOutlined,
  } from '@ant-design/icons-vue';
  import { Row, Col, Popconfirm, Image } from 'ant-design-vue';
  import { useUserStore } from '/@/store/modules/user';
  import { isArray } from '/@/utils/is';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useDrawer } from '/@/components/Drawer';
  import { getFlowInit } from '/@/api/process/process';
  import ProcessDrawer from '../processManagement/processDrawer.vue';
  import ProcessShowDrawer from '../processManagement/processShowDrawer.vue';
  import { getParams } from '/@/utils/utils';
  import * as useFormJsFunc from '/@/assets/form_js';
  import { useGo } from '/@/hooks/web/usePage';
  import GiveLike from './modules/giveLike.vue';
  import { useI18n } from '/@/hooks/web/useI18n';

  export default defineComponent({
    name: 'TileList',
    components: {
      BasicTable,
      SettingOutlined,
      Row,
      Col,
      DeleteOutlined,
      PlusOutlined,
      EditOutlined,
      Popconfirm,
      Image,
      ProcessDrawer,
      ProcessShowDrawer,
      GiveLike,
    },
    props: {
      listPageInfo: {
        type: Object,
        default: () => {
          return {};
        },
      },
      treeNodeCode: {
        type: String,
        default: '',
      },
      isTreeView: {
        type: Boolean,
        default: false,
      },
    },
    emits: ['handle-manager', 'handle-add', 'handle-edit', 'handle-click'],
    setup(props, { emit }) {
      const columns = ref([
        {
          key: 'name',
          detaIndex: 'name',
          title: '',
        },
      ]);
      const [registerProcessShowDrawer, { openDrawer: openProcessShowDrawer }] = useDrawer();
      const [registerProcessDrawer, { openDrawer: openProcessDrawer }] = useDrawer();
      const go = useGo();
      const { t } = useI18n();

      const { createMessage, createConfirm } = useMessage();
      const userStore = useUserStore();
      const serverInfo = userStore.getServerInfo;
      const baseUrl = computed(() =>
        serverInfo.rootPath?.endsWith('/') ? serverInfo.rootPath : `${serverInfo.rootPath}/`,
      );
      const canAdd = computed(() => props.listPageInfo.isBtnAddShow);
      const canEdit = computed(() => props.listPageInfo.isBtnEditShow);
      const canDel = computed(() => props.listPageInfo.isBtnDelShow);
      const btnAddName = computed(() => props.listPageInfo.btnAddName || '新增');
      const btnEditName = computed(() => props.listPageInfo.btnEditName || '编辑');
      const btnDelName = computed(() => props.listPageInfo.btnDelName || '删除');
      const listPage = ref<Recordable>({});
      const pageSetup = ref<Recordable[]>([]);
      const searchForm = ref({
        moduleCode: '',
      });

      const isListRelate = ref(false);
      const getListUrl = computed(() => {
        return isListRelate.value ? getVisualListRelate : getVisualList;
      });

      const fetch = async (params, isRelate = false) => {
        isListRelate.value = isRelate;
        console.log('isListRelate.value', isListRelate.value);

        await nextTick();

        listPage.value = props.listPageInfo;
        console.log('fetch listPage', listPage.value);

        setProps({ api: getListUrl.value, title: unref(listPage)?.moduleName });

        pageSetup.value = unref(listPage).pageSetup || [];
        pageSetup.value.forEach((item) => {
          if (isArray(item.blocks)) {
            item.blocks.forEach((col) => {
              col.style = {
                backgroundColor: col.bgColor ? col.bgColor : 'transparent',
                font: col.font ? col.font : '',
                fontSize: col.fontSize ? col.fontSize + 'px' : '14px',
                fontWeight: col.isBold == 'true' ? 'bold' : '400',
                color: col.fontColor,
                textAlign: col.align ? col.align : 'left',
                paddingTop: col.paddingTop ? col.paddingTop + 'px' : '0',
                paddingBottom: col.paddingBottom ? col.paddingBottom + 'px' : '0',
                paddingLeft: col.paddingLeft ? col.paddingLeft + 'px' : '0',
                paddingRight: col.paddingRight ? col.paddingRight + 'px' : '0',
                marginTop: col.marginTop ? col.marginTop + 'px' : '0px',
                marginRight: col.marginRight ? col.marginRight + 'px' : '0',
                marginBottom: col.marginBottom ? col.marginBottom + 'px' : '0',
                marginLeft: col.marginLeft ? col.marginLeft + 'px' : '0',
                width: '100%',
              };
              if (col.type == 'field') {
                col.style.width = '100%';
                col.style.height = '100%';
              }

              if (col.bgImgUrl) {
                col.style.background = 'url(' + unref(baseUrl) + col.bgImgUrl + ') no-repeat';
                col.style.backgroundSize = '100% 100%';
              }
            });
          }
        });
        if (listPage.value.isColCheckboxShow) {
          setProps({
            rowSelection: {
              type: 'checkbox',
            },
          });
        }
        if (!listPage.value.isPagination) {
          setProps({
            pagination: false,
          });
        }

        setPagination({
          pageSize: listPage.value.pageSize,
        });

        searchForm.value = {
          ...params,
        };
        let c_height = window.innerHeight - 190;
        if (document.getElementById('customForm')?.clientHeight) {
          c_height = c_height - document.getElementById('customForm')?.clientHeight;
        }
        setProps({
          scroll: {
            y: c_height,
          },
        });
        console.log('reload', reload);

        reload();
      };

      onMounted(async () => {
        await nextTick();
        // try {
        //   searchData();
        // } catch (e) {
        //   console.log('searchDataerr', e);
        // }
      });

      const [registerTable, { reload, setProps, getSelectRowKeys, getSelectRows, setPagination }] =
        useTable({
          title: unref(listPage)?.moduleName,
          // api: '', // getListUrl.value,
          columns,
          formConfig: {
            labelWidth: 120,
            schemas: [],
          },
          rowKey: 'id',
          useSearchForm: false,
          showTableSetting: false,
          bordered: false,
          striped: false,
          indexColumnProps: { width: 50 },
          showIndexColumn: false,
          immediate: false,
          clickToRowSelect: false,
          beforeFetch: (info) => {
            let newInfo = info;
            newInfo = Object.assign({}, newInfo, searchForm.value);
            return newInfo;
          },
          afterFetch: (data) => {
            // if (isArray(data) && data.length > 0 && isArray(data[0].colOperate)) {
            //   data[0].colOperate.forEach((item) => {
            //     if (item.type == 'EDIT' && !canEdit.value) {
            //       canEdit.value = true;
            //       btnEditName.value = item.name;
            //     }
            //   });
            // }
          },
          // actionColumn: {
          //   width: 120,
          //   title: '操作',
          //   dataIndex: 'action',
          //   slots: { customRender: 'action' },
          //   fixed: 'right',
          // },
        });

      function handleSuccess() {
        reload();
      }

      const handleManager = () => {
        emit('handle-manager');
      };
      const handleAdd = () => {
        emit('handle-add');
      };

      //批量删除
      const deleteBatch = async () => {
        let keys = getSelectRowKeys();
        if (keys.length == 0) {
          createMessage.warning('请选择需要删除的数据');
          return;
        }
        await getVisualDel({
          ids: keys.join(','),
          moduleCode: listPage.value.moduleCodeRelated
            ? listPage.value.moduleCodeRelated
            : listPage.value.moduleCode,
          treeNodeCode: props.treeNodeCode,
          isTreeView: props.isTreeView,
        }).then(() => {
          handleSuccess();
        });
      };

      //单个删除
      function handleDelete(record: object) {
        createConfirm({
          iconType: 'info',
          title: () => h('span', t('common.prompt')),
          content: () => h('span', '您确定要删除么'),
          onOk: async () => {
            getVisualDel({
              ids: record['id'],
              moduleCode: listPage.value.moduleCodeRelated
                ? listPage.value.moduleCodeRelated
                : listPage.value.moduleCode,
              treeNodeCode: props.treeNodeCode,
              isTreeView: props.isTreeView,
            }).then(() => {
              handleSuccess();
            });
          },
        });
      }

      const handleEdit = () => {
        let keys = getSelectRowKeys();
        if (keys.length != 1) {
          createMessage.warning('请选择一条数据');
          return;
        }
        const record = getSelectRows()[0];
        emit('handle-edit', record);
      };

      const handleClick = (row) => {
        emit('handle-click', row);
      };

      /**
       * 跳转到其它模块，用于二次开发
       * goTo('/smartModulePage', {
       *  moduleCode: 'xmxxgl',
       *  xm: xmId,
       * })
       */
      function goTo(path: string, query: any) {
        go({
          path,
          query,
        });
      }

      function handleColOperate(col, record) {
        console.log('col.btnName', col.btnName);
        console.log('record', record);
        let item = record['colOperate'].filter((it) => col.btnName == it.name)[0];
        console.log('handleColOperate item', item);
        if (item.type == 'FLOW_SHOW') {
          // 查看流程详情
          openProcessShowDrawer(true, {
            flowId: item.flowId,
            visitKey: item.visitKey,
          });
        } else if (item.type == 'FLOW') {
          // 发起流程
          let params = {
            op: 'opLinkFlow',
            typeCode: item.flowTypeCode,
            ...item,
          };
          getFlowInit(params).then((res) => {
            let myActionId = res.myActionId || '';
            if (myActionId) {
              openProcessDrawer(true, {
                myActionId: myActionId,
                type: res.type,
              });
            }
          });
        } else if (item.type == 'MODULE') {
          goTo('/smartModulePage', {
            moduleCode: item.moduleCode,
            moduleId: record.id,
          });
        } else if (item.type == 'CLICK') {
          // 如果存在动态引入的js
          if (typeof useFormJsFunc[listPage.value.formCode] === 'function') {
            console.log('CLICK launch script');
            const funcs = [reload];
            useFormJsFunc[listPage.value.formCode](item.script, funcs).then((ret) => {
              console.log('useFormJsFunc[' + listPage.value.formCode + ']', ret);
              if (!ret) {
                console.log('CLICK eval script after useFormJsFunc');
                // 调用外部 js
                try {
                  eval(item.script);
                } catch (e) {
                  console.warn(item.name, e);
                }
              }
            });
          } else {
            // 调用外部 js
            console.log('CLICK eval script');
            try {
              eval(item.script);
            } catch (e) {
              console.warn(item.name, e);
            }
          }
        } else if (item.type == 'LINK') {
          let params = getParams(item.link);
          goTo(item.link, { ...params });
        } else if (item.type == 'DEL') {
          handleDelete(record);
        } else if (item.type == 'EDIT') {
          emit('handle-edit', record);
        }
      }

      return {
        registerTable,
        handleSuccess,
        listPage,
        handleManager,
        fetch,
        pageSetup,
        baseUrl,
        handleAdd,
        canAdd,
        canDel,
        canEdit,
        btnAddName,
        btnDelName,
        btnEditName,
        deleteBatch,
        handleEdit,
        handleClick,
        handleColOperate,
        registerProcessShowDrawer,
        registerProcessDrawer,
      };
    },
  });
</script>
<style lang="less" scoped>
  .overflow_text {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .line {
    width: 100%;
    height: 1;
    margin: 20rpx 0;
    border-top: 1px solid #eee;
  }
  :deep(.ant-table-header) {
    height: 1px;
  }
  :deep(.ant-table-tbody > tr > td) {
    border: none;
    background: none !important;
  }
</style>
